<template>
  <div class="chat-topic-list">
    <div class="topic-header">
      <h3 class="header-title">对话历史</h3>
      <el-button 
        type="primary" 
        size="small" 
        plain
        @click="createNewTopic"
      >
        <i class="fa fa-plus"></i>
        新建对话
      </el-button>
    </div>
    
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索对话主题..."
        clearable
        prefix-icon=""
        size="small"
      />
    </div>
    
    <div class="topic-list-container">
      <div v-if="filteredTopics.length === 0" class="empty-topics">
        <div v-if="props.topics.length === 0">
          <i class="fa fa-comments-o"></i>
          <p>暂无对话记录</p>
          <el-button type="primary" size="small" @click="createNewTopic">
            开始新对话
          </el-button>
        </div>
        <div v-else>
          <i class="fa fa-search"></i>
          <p>未找到匹配的对话主题</p>
        </div>
      </div>
      
      <template v-else>
        <div 
          v-for="topic in filteredTopics" 
          :key="topic.id"
          class="topic-item"
          :class="{ 'active': topic.id === props.activeTopicId }"
          @click="selectTopic(topic.id)"
        >
          <div class="topic-content">
            <div class="topic-title" :title="topic.title">
              {{ topic.title }}
            </div>
            <div class="topic-meta">
              <span class="message-count">
                {{ topic.message_count }} 条消息
              </span>
              <span class="time">
                {{ formatTime(topic.last_message_time) }}
              </span>
            </div>
          </div>
          
          <div class="topic-actions">
            <el-dropdown trigger="click" @command="handleCommand($event, topic.id)">
              <i class="fa fa-ellipsis-v"></i>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="rename">
                    <i class="fa fa-edit"></i> 重命名
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <i class="fa fa-trash" style="color: #f56c6c;"></i> 
                    <span style="color: #f56c6c;">删除</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
    </div>
    
    <!-- 重命名对话框 -->
    <el-dialog
      v-model="renameDialog.visible"
      title="重命名对话"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-input 
        v-model="renameDialog.title" 
        placeholder="请输入新的对话名称"
        maxlength="50"
        show-word-limit
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialog.visible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmRename" 
            :disabled="!renameDialog.title.trim()"
          >确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 新建对话框 -->
    <el-dialog
      v-model="createDialog.visible"
      title="新建对话"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-input 
        v-model="createDialog.title" 
        placeholder="请输入对话名称（可选）"
        maxlength="50"
        show-word-limit
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialog.visible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmCreate"
          >创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';

dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

// 定义属性
const props = defineProps({
  topics: {
    type: Array,
    default: () => []
  },
  activeTopicId: {
    type: [Number, String],
    default: null
  }
});

// 定义事件
const emit = defineEmits(['topic-selected', 'topic-created', 'topic-renamed', 'topic-deleted']);

// 状态管理
const searchKeyword = ref('');
const renameDialog = ref({
  visible: false,
  topicId: null,
  title: ''
});
const createDialog = ref({
  visible: false,
  title: ''
});

// 过滤后的主题列表
const filteredTopics = computed(() => {
  if (!searchKeyword.value.trim()) {
    return props.topics;
  }
  
  const keyword = searchKeyword.value.toLowerCase();
  return props.topics.filter(topic => 
    topic.title.toLowerCase().includes(keyword)
  );
});

// 选择主题
function selectTopic(topicId) {
  emit('topic-selected', topicId);
}

// 创建新主题
function createNewTopic() {
  createDialog.value.visible = true;
  createDialog.value.title = '';
}

// 确认创建主题
function confirmCreate() {
  const title = createDialog.value.title.trim() || '新对话';
  emit('topic-created', title);
  createDialog.value.visible = false;
}

// 处理命令
function handleCommand(command, topicId) {
  if (command === 'rename') {
    openRenameDialog(topicId);
  } else if (command === 'delete') {
    confirmDelete(topicId);
  }
}

// 打开重命名对话框
function openRenameDialog(topicId) {
  const topic = props.topics.find(t => t.id === topicId);
  if (topic) {
    renameDialog.value.topicId = topicId;
    renameDialog.value.title = topic.title;
    renameDialog.value.visible = true;
  }
}

// 确认重命名
function confirmRename() {
  const title = renameDialog.value.title.trim();
  if (title) {
    emit('topic-renamed', renameDialog.value.topicId, title);
    renameDialog.value.visible = false;
  }
}

// 确认删除
function confirmDelete(topicId) {
  ElMessageBox.confirm(
    '确认删除此对话？删除后无法恢复。',
    '删除对话',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    emit('topic-deleted', topicId);
  }).catch(() => {});
}

// 格式化时间
function formatTime(timeString) {
  if (!timeString) return '';
  
  const date = dayjs(timeString);
  const now = dayjs();
  
  // 今天内显示时:分
  if (date.isSame(now, 'day')) {
    return date.format('HH:mm');
  }
  
  // 昨天显示"昨天"
  if (date.isSame(now.subtract(1, 'day'), 'day')) {
    return '昨天';
  }
  
  // 本周内显示周几
  if (date.isAfter(now.startOf('week'))) {
    return date.format('ddd');
  }
  
  // 本年内显示月-日
  if (date.isSame(now, 'year')) {
    return date.format('MM-DD');
  }
  
  // 其他显示年-月-日
  return date.format('YYYY-MM-DD');
}
</script>

<style scoped>
.chat-topic-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.topic-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.search-container {
  padding: 8px 16px;
  border-bottom: 1px solid #ebeef5;
}

.topic-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.topic-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  border-left: 3px solid transparent;
  justify-content: space-between;
}

.topic-item:hover {
  background-color: #f0f2f5;
}

.topic-item.active {
  background-color: #ecf5ff;
  border-left-color: #409eff;
}

.topic-content {
  flex: 1;
  min-width: 0; /* 确保内容不会超出容器 */
}

.topic-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.topic-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.message-count {
  flex-shrink: 0;
}

.time {
  margin-left: 8px;
  flex-shrink: 0;
}

.topic-actions {
  display: flex;
  align-items: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.topic-item:hover .topic-actions {
  opacity: 1;
}

.topic-actions i {
  cursor: pointer;
  color: #909399;
  padding: 4px;
  border-radius: 4px;
}

.topic-actions i:hover {
  color: #606266;
  background-color: rgba(0, 0, 0, 0.05);
}

.empty-topics {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 24px;
  color: #909399;
  text-align: center;
}

.empty-topics i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #dcdfe6;
}

.empty-topics p {
  margin: 0 0 16px 0;
}
</style> 